#include "CShield.h"
#include "GamePlayScene.h"
#include "MainLayer.h"
USING_NS_CC;

CShield::CShield() :
	_pShip(NULL)
{
}

/**
 * @param pShip The ship is created and release by the MainLayer.
 * @param frameNamePrefix The frame prefix for the shield sprite.
 * @param pSpriteSheet This parameter is created and released by the MainLayer.
 *
 * @return true if the sprite was initialized without problems, false otherwise.
 */

bool CShield::init(CShip* pShip, char* frameNamePrefix, cocos2d::CCSpriteBatchNode* pSpriteSheet, b2World* pWorld)
{
	if(!CAnimatedObject::init(frameNamePrefix, pSpriteSheet, pWorld))
	{
		return false;
	}

	_pShip = pShip;

	this->setTag(MainLayer::shieldTag);
	createBoxBody();

	return true;
}

/**
 * Display the hit flash and restore the previous sprite.
 */
void
CShield::hit()
{
	this->setDisplayFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("shipShieldHit1.png"));
	this->runAction(CCSequence::actions(CCDelayTime::actionWithDuration(0.7f),
					CCCallFunc::actionWithTarget(this, callfunc_selector(CShield::restoreSprite)),
					NULL));
}

/**
 * Restore the original shield sprite.
 */
void
CShield::restoreSprite()
{
	this->setDisplayFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("shipShieldNormal1.png"));
}

void
CShield::createBoxBody()
{
    b2BodyDef spriteBodyDef;
    spriteBodyDef.type = b2_dynamicBody;
    spriteBodyDef.active = true;
    float x = this->getPosition().x / P2M;
    float y = this->getPosition().y / P2M;
    spriteBodyDef.position.Set(x, y);
    spriteBodyDef.userData = this;
    _pBody = _pWorld->CreateBody(&spriteBodyDef);

    CCPoint anchor = this->getAnchorPoint();
    //The shield and ship centers aren't aligned so shield's body has to be moved by a few pixels.
    float shapeX = this->boundingBox().size.width * (0.5f - anchor.x) / P2M;

    b2CircleShape spriteShape;
    spriteShape.m_radius = 42.0f / P2M;
    spriteShape.m_p = b2Vec2(shapeX, 0.0f);
    b2FixtureDef spriteShapeDef;
    spriteShapeDef.shape = &spriteShape;
    spriteShapeDef.density = 1.0;
    spriteShapeDef.restitution = 0.5f;
    spriteShapeDef.filter.categoryBits = ECategoryBit::shieldCategoryBit;
    spriteShapeDef.filter.maskBits = ECategoryBit::enemyCategoryBit;

    _pBody->CreateFixture(&spriteShapeDef);
}

void
CShield::collision(float damage)
{
	_pShip->collision(damage);
}
